package experiment2.task3;


import experiment2.task1.Person;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;

/**
 * @author 冯永龙
 * @date 2021/3/23 11:19
 */
public class MyInvocationHandler implements InvocationHandler {
    private Object object = null; //记录委托对象
    private ArrayList<String> log = new ArrayList<String>();
    private String date;

    public ArrayList<String> getLog() {
        return log;
    }

    public Object bind(Object object){
        this.object = object;
        return Proxy.newProxyInstance(
                MyInvocationHandler.class.getClassLoader(),
                object.getClass().getInterfaces(),
                this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String str = "";
        Iterator<Object> iterator = Arrays.stream(args).iterator();

        while (iterator.hasNext()){
            str += iterator.next().toString();

        }

        log.add("时间："+date+";方法名称："+method.getName()+";参数："+str) ;
        Object result = method.invoke(this.object,args);
        return result;
    }
}

